package com.chen.cloudpicture.manager.websocket.disruptor;

import cn.hutool.core.thread.ThreadFactoryBuilder;
import com.lmax.disruptor.dsl.Disruptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * 图片编辑事件 Disruptor 配置
 */
@Configuration
public class PictureEditEventDisruptorConfig {

    @Resource
    private PictureEditEventWorkHandler pictureEditEventWorkHandler;

    // 初始化 disruptor 队列
    @Bean("PictureEditEventDisruptor")
    public Disruptor<PictureEditEvent> messageModelRingBuffer() {
        // 定义 ringBuffer 的大小
        /**
         * disruptor 并发量小时性能提升并不明显，并发越大性能越好，环形缓冲区太小也容易被占满避免覆盖而等待，不过太大也会占用空间
         * 一般如果要用环形缓冲区并发起码都到万级以上，我们这里定义一个百万级，队列大小根据情况定义
         */
        int bufferSize = 1024 * 256;
        // 创建 disruptor 队列
        Disruptor<PictureEditEvent> disruptor = new Disruptor<>(
                PictureEditEvent::new, // 事件类型
                bufferSize,// 缓冲区大小
                ThreadFactoryBuilder.create() // 线程工厂
                        .setNamePrefix("PictureEditEventDisruptor") //指定线程前缀
                        .build()
        );
        // 绑定消费者
        disruptor.handleEventsWithWorkerPool(pictureEditEventWorkHandler);
        // 启动 disruptor
        disruptor.start();
        return disruptor;
    }

}
